package org.example.rabbitmq.exchangeDirect;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer {
    public static void main(String[] args) throws Exception {
        // 1: 创建连接工厂，设置连接属性
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        // 2: 创建连接，获取通道
        Connection connection = connectionFactory.newConnection("生产者");
        Channel channel = connection.createChannel();

        // 3: 定义队列名称-随机生成队列名、交换机名、路由key（fanout模式时路由key为空字符串）
        String exchangeName = "direct-exchange";

        // 4-1: 声明交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT);
        // 4-2: 声明队列
        channel.queueDeclare("direct-info", false, false, false, null);
        channel.queueDeclare("direct-error", false, false, false, null);
        // 4-3: 绑定交换机和队列
        channel.queueBind("direct-info", exchangeName, "info");
        channel.queueBind("direct-error", exchangeName, "error");

        // 5: @params1: 交换机名  @params2 队列/路由key @params 属性配置  @params4 消息内容
        channel.basicPublish(exchangeName, "info", null, "你好，消息队列！info".getBytes("UTF-8"));
        channel.basicPublish(exchangeName, "error", null, "你好，消息队列！error".getBytes("UTF-8"));

        System.out.println("消息发送成功!");

        // 最后关闭通关和连接
        channel.close();
        connection.close();
    }
}
